package com.madrivergroup.mamatodo.dao;

import java.util.ArrayList;
import java.util.List;

import com.madrivergroup.mamatodo.tasks.Task;
import com.madrivergroup.mamatodo.util.MaMaUtil;

import android.content.ContentValues;
import android.content.Context;
import android.database.Cursor;
import android.database.sqlite.SQLiteDatabase;
import android.database.sqlite.SQLiteOpenHelper;
import android.util.Log;


/**
 * Implements the ITaskDao with an SQLite persistenace storage
 * 
 * @author peterdelaney
 *
 */
public class TaskDaoSqlite extends SQLiteOpenHelper implements ITaskDao {

	
	protected static final String NAME =  TaskDaoSqlite.class.getSimpleName();
	
	private static String LOG_NAME      = TaskDaoSqlite.class.getName();
	private static String TASK_ID            = "TASK_ID";
	private static String TASK_NAME          = "TASK_NAME";
	private static String TASK_COMPLETE      = "TASK_COMPLETE";
	private static String TASK_CREATE_DATE   = "CREATE_DATE";
	public static  String DB_NAME            = "TASKS_DB";
	public static  String TABLE_NAME         = "TASKS_TABLE";
	public static  int    VERSION            = 2;
	
	
	protected SQLiteDatabase  databaseInstance = null;
	
	// GOing to keep local copy and save when app is about to close
	protected List<Task>  listOfTasks = new ArrayList<Task>();

	/**
	 * Constructor to create this class
	 * @param context
	 */
	public TaskDaoSqlite(Context context ) {
		super(context, DB_NAME, null, VERSION );
	
		// Create Instance to Database
		databaseInstance = getWritableDatabase();
	}

	/* (non-Javadoc)
	 * @see android.database.sqlite.SQLiteOpenHelper#onCreate(android.database.sqlite.SQLiteDatabase)
	 */
	@Override
	public void onCreate(SQLiteDatabase db) {
		Log.d(LOG_NAME, NAME + ":onCreate()");
		createTables(db);
	}

	/* (non-Javadoc)
	 * @see android.database.sqlite.SQLiteOpenHelper#onUpgrade(android.database.sqlite.SQLiteDatabase, int, int)
	 */
	@Override
	public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {
		Log.d(LOG_NAME, NAME + ":onUpgrade()");		
		
	}

	/**
	 * Implementation ITaskDao
	 */
	public void addTask(Task t) {
		Log.d(LOG_NAME, NAME + ":addTask( " + t + " )");
		saveTask( t );
	}

	public List<Task> getTaskList() {
		Log.d(LOG_NAME, NAME + ":getTaskList()");
		return loadTasks();
	}
	
	public List<Task> getTasksByComplete( boolean f ) {
		Log.d(LOG_NAME, NAME + ":getTasksByComplete()");
		return loadTasks();		
	}

	public void removeTask(Task t) {
		Log.d(LOG_NAME, NAME + ":removeTask( " + t.getId() + " )");

		SQLiteDatabase db = getWritableDatabase();
		int idRemoved = 0;
		try {
			idRemoved = db.delete(TABLE_NAME, TASK_ID + "=" + t.getId(), null );
			Log.i(LOG_NAME, "ID Removed :" + idRemoved );
			db.close();
		}
		catch( Exception ex ) {
			Log.d(LOG_NAME, ex.getMessage() );
			Log.e(LOG_NAME, Log.getStackTraceString(ex));			
		}
		
	} // end of removeTask()
	
	
	/**
	 * Deletes a list of Tasks
	 * @param ids
	 */
	public void deleteTasks( long[] ids) {
		Log.d(LOG_NAME, NAME + ":deleteTasks()");

		// Create the IN portion of the WHERE clause
		StringBuffer id = new StringBuffer();
		for( int i = 0; i < ids.length; i++ ) {
			id.append(ids[i]);
			if( i < ids.length - 1 ) {
				id.append(",");
			}
		}
		Log.i(LOG_NAME, NAME + "ids=" + id );
		
		SQLiteDatabase db = getWritableDatabase();
		String WHERE = TASK_ID + " IN (" + id + " )";
		
		try {
			db.delete(TABLE_NAME, WHERE, null );
			db.close();			
		}
		catch( Exception ex ) {
			Log.d(LOG_NAME, ex.getMessage() );
			Log.e(LOG_NAME, Log.getStackTraceString(ex));			
		}
		

		
	} // end of deleteTasks()
	

	public void saveTask(Task t) {
		Log.d(LOG_NAME, NAME + ":saveTask( " + t + " )");
		
		ContentValues values = new ContentValues();
		values.put(TASK_NAME, t.getName() );
		values.put(TASK_COMPLETE, String.valueOf(t.isComplete() ) );
		values.put(TASK_CREATE_DATE, MaMaUtil.convertToString( t.getCreateDate() ) );
		
		SQLiteDatabase db = getWritableDatabase();
		long id = db.insert(TABLE_NAME, null, values);
		db.close();
		
		t.setId( id );
		listOfTasks.add( t );
	}

	public void saveTaskList(List<Task> l) {
		Log.d(LOG_NAME, NAME + ":saveTaskList()");
	}
	
	/**
	 * Creates the tables
	 */
	protected void createTables(SQLiteDatabase db ) {
		Log.d(LOG_NAME, NAME + ":createTables()");
		
		String CREATE_SQL = "CREATE TABLE " + TABLE_NAME + " ( " + 
			TASK_ID + " INTEGER PRIMARY KEY autoincrement NOT NULL ," +
			TASK_NAME        + " TEXT ," +
			TASK_COMPLETE    + " TEXT ," +
			TASK_CREATE_DATE + " TEXT " +
			" ) ";
		
		try {
			db.execSQL( CREATE_SQL );
		}
		catch( Exception ex ) {
			Log.e(LOG_NAME, ex.getMessage() );
			ex.printStackTrace();
		}
		
	} // end of createTables()
	
	/**
	 * Helper method to load up list from the tables.
	 * 
	 * @return
	 */
	protected List<Task> loadTasks() {
		Log.d(LOG_NAME, NAME + ":loadTasks()");

		// Clean out before retrieving fresh list
		listOfTasks.clear();
		
		String[] columns = new String[] {
				TASK_ID,
				TASK_NAME,
				TASK_COMPLETE,
				TASK_CREATE_DATE
		};

		
		SQLiteDatabase db = null;
		Cursor cursor =  null;
		try {
			db = getReadableDatabase(); 			
			cursor = db.query(TABLE_NAME, 
					columns, 
					null, null, null, null, 
					String.format("%s, %s", TASK_NAME, TASK_ID )  // order by 
				);
			cursor.moveToFirst();
		
		Task t = null;
		if( ! cursor.isAfterLast() ) {
			do {
				int id = cursor.getInt(0);
				String name = cursor.getString(1);
				String boolVal = cursor.getString(2);
				boolean comp = Boolean.parseBoolean( boolVal );
				String dt = cursor.getString(3);				
				t = new Task(name);
				t.setId( id );
				t.setComplete( comp );
				t.setCreateDate( MaMaUtil.convertToDate( dt ) );
				listOfTasks.add( t );
			} while (cursor.moveToNext() );
		}
		cursor.close();
		}
		catch( Exception ex ) {
			Log.e(LOG_NAME, NAME + ex.getMessage() );
			Log.e(LOG_NAME, Log.getStackTraceString(ex));
		}
		
		return listOfTasks;
	} // end of loadTasks()


	
} // end of TaskDaoSqlite class
